package com.demo.core;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.*;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

/**
 * 全局设置
 */
public class SysConfig {

    private static String webroot = null;

    public static String getLocalIp() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
            return addr.getHostAddress().toString(); //获取本机ip
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }

    public static String getLocalIfconfig() {
        List<String> ips = new ArrayList<String>();
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress())
                        ips.add(inetAddress.getHostAddress().toString());
                }
            }
        } catch (SocketException ex) {
        }
        return StringUtils.join(ips, ",");
    }

    public static String getLocalHost() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
            return addr.getHostName().toString(); //获取本机计算机名称
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "web";
    }

    /**
     * /root/exchange2/file:/root/exchange2/exchange2.jar!/BOOT-INF/classes!
     *
     * @return
     */
    public static String initWebroot() {
        URL url = SysConfig.class.getProtectionDomain().getCodeSource()
                .getLocation();
        String classpath = null;
        try {
            classpath = URLDecoder.decode(url.getPath(), Constants.ENCODE_UTF8);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        if (classpath.endsWith(".jar")) {
            classpath = classpath.substring(0,
                    classpath.lastIndexOf(Constants.MARK_SLASH));
        }
        File file = new File(classpath);
        classpath = file.getAbsolutePath();
        if (classpath.indexOf("classes") != -1) {
            if (classpath.contains("file:"))
                classpath = classpath.substring(0, classpath.indexOf("file:"));
            else classpath = classpath.replace("form" + Constants.FILE_SEPERATOR
                    + "WEB-INF" + Constants.FILE_SEPERATOR + "classes", "");
        }
        webroot = classpath;
        return webroot;
    }

    public static String getWebroot() {
        return webroot;
    }

    public static void setWebroot(String webroot) {
        SysConfig.webroot = webroot;
    }

    /**
     * 递归创建路径
     *
     * @param srcdir
     */
    public static void mkdirs(String srcdir) {
        File dir = new File(srcdir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 拷贝文件夹
     *
     * @param srcdir
     * @param todir
     */
    public static void copyDir(String srcdir, String todir) {
        File dir = new File(srcdir);
        if (!dir.isDirectory()) {
            FileChannel in = null;
            FileChannel out = null;
            try {
                in = (new FileInputStream(srcdir)).getChannel();
                out = (new FileOutputStream(todir)).getChannel();
                in.transferTo(0, in.size(), out);
            } catch (IOException e) {
            } finally {
                try {
                    out.close();
                    in.close();
                } catch (IOException e) {
                }
            }
            return;
        }
        mkdirs(todir);
        File[] files = dir.listFiles();
        for (File file : files) {
            copyDir(SysConfig.concat(srcdir, file.getName()),
                    SysConfig.concat(todir, file.getName()));
        }
    }

    /**
     * 拷贝文件
     *
     * @param srcfile
     * @param todir
     * @param tofilename
     */
    public static void copyFile(String srcfile, String todir, String tofilename) {
        mkdirs(todir);
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = (new FileInputStream(srcfile)).getChannel();
            out = (new FileOutputStream(concat(todir, tofilename)))
                    .getChannel();
            in.transferTo(0, in.size(), out);
        } catch (IOException e) {
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * 用指定的内容保存为一个文件
     *
     * @param content
     * @param todir
     * @param tofilename
     */
    public static void saveFile(String content, String todir, String tofilename) {
        mkdirs(todir);
        FileWriter writer = null;
        try {
            writer = new FileWriter(concat(todir, tofilename));
            writer.write(content);
            writer.flush();
        } catch (IOException e) {

        } finally {
            try {
                writer.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 递归删除文件，支持目录
     *
     * @param file
     */
    public static void removeFile(String file) {
        File dir = new File(file);
        if (!dir.exists())
            return;
        if (dir.isDirectory()) {
            String[] files = dir.list();
            for (String f : files)
                removeFile(file + Constants.FILE_SEPERATOR + f);
        }
        dir.delete();
    }

    /**
     * 获取文件名，不带后缀
     *
     * @param srcfile
     * @return
     */
    public static String getFilename(String srcfile) {
        int i = srcfile.lastIndexOf(Constants.FILE_SEPERATOR);
        int j = srcfile.lastIndexOf(Constants.MARK_DOT, i);
        return srcfile.substring(i + 1, j);
    }

    /**
     * 获取文件名，带后缀
     *
     * @param srcfile
     * @return
     */
    public static String getFilenameEx(String srcfile) {
        int i = srcfile.lastIndexOf(Constants.FILE_SEPERATOR);
        return srcfile.substring(i + 1);
    }

    /**
     * 拼接路径
     *
     * @param dir
     * @param subdir
     * @return
     */
    public static String concat(String dir, String... subdir) {
        String seperator = Constants.FILE_SEPERATOR;
        if (dir.startsWith("/"))
            seperator = "/";
        List<String> subdirs = Arrays.asList(subdir);
        StringBuffer sb = new StringBuffer();
        if (dir.endsWith(seperator))
            sb.append(dir.substring(0, dir.length() - seperator.length()));
        else
            sb.append(dir);
        for (int i = 0; i < subdirs.size(); i++) {
            if (subdirs.get(i).startsWith(seperator))
                sb.append(subdirs.get(i));
            else
                sb.append(seperator).append(subdirs.get(i));
        }
        return sb.toString();
    }

    public static String toString(Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }

    public static void out(int msg) {
        System.out.println(Constants.DOC_PREFIX + msg);
    }

    public static void out(String msg) {
        System.out.println(Constants.DOC_PREFIX + msg);
    }

    public static void out(List<String> msg) {
        System.out.println(Constants.DOC_PREFIX + msg.toString());
    }

    public static void out(String[] msg) {
        System.out.println(Constants.DOC_PREFIX + Arrays.toString(msg));
    }

    public static void out(Object msg) {
        System.out.println(Constants.DOC_PREFIX + msg);
    }

    public static void main(String[] args) {
        out(getLocalIp());
    }
}
